<template>
  <custom-dialog
    ref="dialog" width="460px"
    :title="modalTitle"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <el-form ref="form" :model="info" :rules="rules">
      <el-form-item label="上级">
        <el-input v-model="info.superiorName" disabled></el-input>
      </el-form-item>
      <el-form-item label="字典名称" prop="dicName">
        <el-input v-model="info.dicName" @input="onInput"></el-input>
      </el-form-item>
      <el-form-item label="字典编码" prop="dicCode">
        <el-input v-model="info.dicCode"></el-input>
      </el-form-item>
    </el-form>
  </custom-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import CustomDialog from '@/components/custom-dialog'
import { saveOrUpdateDictionaryGroup } from '@/api/sysDictionaryGroup'

const api = {
  saveOrUpdateDictionaryGroup
}
export default {
  name: 'group-operate-modal',
  props: {
    modalTitle: String,
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  components: { CustomDialog },
  data () {
    return {
      info: {
        id: '',
        dicName: '',
        dicCode: '',
        superiorId: '',
        superiorName: ''
      },
      rules: {
        dicName: [{ required: true, message: '请输入字典名称' }],
        dicCode: [{ required: true, message: '请输入字典编码' }]
      }
    }
  },
  created () {
    this.onInput = debounce(this.onInput)
  },
  methods: {
    onInput (val) {
      if (val) {
        this.info.dicCode = this.$pinyin_uppercase(val)
      }
    },
    open () {
      const isAdd = this.data.dicName === '' && this.data.dicCode === ''
      this.info = isAdd
        ? this.$options.data().info
        : { ...this.info, ...this.data }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.info.superiorId = this.data.superiorId
      this.info.superiorName = this.data.superiorName
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      return this.$refs.form.validate()
    },
    onConfirm (close) {
      const params = {
        ...this.info
      }
      if (params.id === '') {
        delete params.id
      }
      return api.saveOrUpdateDictionaryGroup(params).then(res => {
        if (res.code === 200) {
          this.$emit('save-success')
          this.$message.success('保存成功')
          close()
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
